<template>
  <el-form :model="salesAttrListForm" ref="formRef">
    <template v-for="(item, index) in salesAttrListForm.salesAttrList" :key="item.attributeId">
      <el-form-item :label="item.attrName"
                    :prop="`salesAttrList[${index}].attributeValues`"
                    :rules="{required: true, message: '请输入属性值', trigger: 'blur'}"
      >
        <el-input-tag
            v-model="item.attributeValues"
            placeholder="请输入属性值"
            clearable
            aria-label="Please click the Enter key after input"
        />
      </el-form-item>
    </template>
  </el-form>
  <el-row :gutter="20">
    <el-col :span="3" :offset="6">
      <div>
        <el-button type="primary" @click="formStore.back()">上一步</el-button>
      </div>
    </el-col>
    <el-col :span="3" :offset="4">
      <div>
        <el-button type="success" @click="next(formRef)">下一步:设置SPU信息</el-button>
      </div>
    </el-col>
  </el-row>
</template>
<script setup lang="ts">
import {onMounted, ref, onUnmounted, reactive} from 'vue'
import {reqGetSkuSaleAttributeListByCategoryId} from '@/api/serve/re-market'
import type {AttributeAndValuesDTO} from '@/api/serve/re-market/type'
import {useGoodsFormStore} from "@/stores/form/goods-form";
import type {FormInstance, FormRules} from "element-plus";

const formStore = useGoodsFormStore()
let formRef = ref<FormInstance>()
//使用响应是对象包裹，可以解决循环表单校验问题
let salesAttrListForm= reactive({
  salesAttrList:[] as AttributeAndValuesDTO[]
})

onMounted(() => {
  //如果表单中为空，表示用户还没填写，则获取数据
  if (formStore.addGoodsForm.saleAttributeList.length === 0) {
    getSkuSaleAttributeListByCategoryId()
  }
  //否则表示用户已经填写了，则直接使用
  else {
    salesAttrListForm.salesAttrList = [...formStore.addGoodsForm.saleAttributeList]
  }
})

let getSkuSaleAttributeListByCategoryId = async () => {
  let res = await reqGetSkuSaleAttributeListByCategoryId(formStore.addGoodsForm.spuInfo.categoryId)
  salesAttrListForm.salesAttrList = res.data
}
let next = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      formStore.next()
    } else {
      console.log('error submit!', fields)
    }
  })
}
onUnmounted(() => {
  //组件卸载的时候提交数据
  formStore.setSaleAttributeList(salesAttrListForm.salesAttrList)
})
</script>
<style scoped>

</style>
